<template>
  <div class="row">
    <q-list style="width: 300px">
      <q-item>
        <q-select
          class="full-width"
          :dark="ui.isDark"
          filled
          v-model="type"
          :options="typeOptions"
          :display-value="` ${
            type.label ? '当前类型：' + type.label : '请选择类型'
          }`"
        >
          <template v-if="type" v-slot:append>
            <q-icon
              name="cancel"
              @click.stop.prevent="type = ''"
              class="cursor-pointer"
            />
          </template>
        </q-select>
      </q-item>
      <q-scroll-area style="width: 100%; height: calc(100vh - 125px)">
        <template v-for="item in postureList" :key="item.id">
          <q-item v-show="!type || item.type === type.value">
            <q-btn
              no-caps
              class="full-width q-pa-none"
              :label="item.name"
              :class="
                activePosture.id === item.id ? ui.activeClass : ui.itemClass
              "
              @click="choosePosture(item)"
            />
          </q-item>
        </template>
      </q-scroll-area>
    </q-list>
    <div
      ref="postureDiv"
      style="width: calc(100vw - 300px); overflow: hidden"
    ></div>
    <list-show-small
      v-if="
        activePosture &&
        activePosture.onCanvas &&
        pixiTool.savedList.filter(
          (item) => item.onCanvas && item.id !== activePosture.id
        ).length
      "
      @update="updateLine"
      @switchChange="(val) => (switchStatus = val)"
      ref="lineListDialog"
      :position="'top:100px'"
      :needReset="false"
      :needSwitch="true"
      :switchStatus="switchStatus"
      :title="activePosture.name || ''"
      :optionsList="pixiTool.savedList.filter((item) => item.onCanvas)"
      :selectedList="activePosture.connected || []"
    />
    <q-dialog seamless v-model="always" persistent position="top">
      <q-card :class="ui.headerClass">
        <q-card-section class="q-gutter-sm content-center">
          <q-btn label="重载" :class="ui.btnClass" @click="loadPosture" />
          <q-btn label="保存" :class="ui.btnClass" @click="saveList" />
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>
<script setup>
import { onBeforeMount, onMounted, ref } from "vue";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api";
import PixiTool from "src/utils/PixiTool";
import ListShowSmall from "components/map/ListShowSmall.vue";
import { useRoute } from "vue-router";
import { useUiStore } from "stores/ui";

const $q = useQuasar();
const ui = useUiStore();
const pixiTool = PixiTool();
const postureDiv = ref();
const lineListDialog = ref();
const activePosture = ref({});
const type = ref("");
const typeOptions = ref([
  {
    label: "准备点",
    value: "home",
  },
  {
    label: "校准点",
    value: "calibration",
  },
  {
    label: "过渡点",
    value: "transition",
  },
  {
    label: "工位点",
    value: "reference",
  },
]);
const postureList = ref([]);
const switchStatus = ref(false); //  查看连线的弹窗是否默认开启
const always = ref(true);
const storageId = ref("");
const route = useRoute();
// ------生命周期----------------------------------------------------------------------
onBeforeMount(() => {
  storageId.value = route.query.id;
});

onMounted(() => {
  initPixi();
});

// 创建画布
function initPixi() {
  pixiTool.div = postureDiv.value;
  pixiTool.stage = pixiTool.createStage(postureDiv.value);
  // 覆写点位点击事件
  pixiTool.clickPoint = choosePosture;
  // 覆写点位移入移出事件
  pixiTool.isOnCanvas = changeCanvas;
  loadBg();
}

// 加载背景
function loadBg() {
  const bgImage = new Image();
  bgImage.src = "posture/bg.png";
  bgImage.onload = () => {
    pixiTool.bg = pixiTool.createBg({
      img: bgImage,
    });
    pixiTool.createArea();
    loadPosture();
    pixiTool.updateStage();
  };
}

function loadPosture() {
  api
    .get(useAPIStore().postureUrl + "new/posture/storage/" + storageId.value)
    .then((rs) => {
      postureList.value = rs.data.data;
      pixiTool.drawRail(postureList.value);
    });
}

// 选中点位
function choosePosture(posture) {
  pixiTool.highlight(posture);
  activePosture.value = pixiTool.highlightPoint;
  // 是否需要连线弹窗
  if (switchStatus.value) {
    // 连线弹窗是否符合条件
    if (lineListDialog.value) lineListDialog.value.show();
  }
}

// 点位进入或移除画布
function changeCanvas(bool) {
  activePosture.value.onCanvas = !bool;
  activePosture.value.onCanvas = bool;
  // 如果点位移除，清除连线
  if (!bool) updateLine([]);
}

// 保存点位
function saveList() {
  api
    .put(useAPIStore().postureUrl + "new/posture/batch", pixiTool.savedList)
    .then((rs) => {
      rs.data.code === 200
        ? $q.notify({
            message: "保存成功",
            type: "positive",
          })
        : $q.notify({
            message: "保存失败",
            type: "negative",
          });
    });
}

// 更新连线
function updateLine(connected) {
  // 将选中点的新连线进行赋值
  activePosture.value.connected = connected;
  pixiTool.savedList.forEach((item) => {
    const index = item.connected.indexOf(activePosture.value.id);
    // 如果其他点对选中点有连接，进行断开，（先统一与选中点进行断开）
    if (index >= 0) item.connected.splice(index, 1);
    // 新连线的点对选中点进行连线
    if (connected.indexOf(item.id) >= 0)
      item.connected.push(activePosture.value.id);
  });
  pixiTool.drawRail();
}
</script>
